package com.example.demovote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demovote.entity.User;
import com.example.demovote.mapper.UserMapper;
import com.example.demovote.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demovote.service.ServiceException;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 投票系统-用户表-4 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User login(String uname, String pwd) throws ServiceException {
        // 验证用户输入
        if(uname==null || uname.trim().isEmpty()){
            throw new ServiceException(-1,"请输入用户名！");
        }
        if(pwd==null || pwd.trim().isEmpty()){
            throw new ServiceException(-2,"请输入密码！");
        }
        if(pwd.length()<3){
            throw new ServiceException(-4,"密码长度不能少于3位！");
        }

        // 查询用户信息
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        // uname = ?
        lqw.eq(User::getUname, uname);
        lqw.eq(User::getPwd, pwd);
        User user = this.getOne(lqw);

        // 判断结果
        if(user == null){
            throw new ServiceException(-3,"用户名或密码错误！");
        }
        return user;
    }

    public void register(User user) throws ServiceException {
        // 查询用户信息
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        // uname = ?
        lqw.eq(User::getUname, user.getUname());
        if(this.count(lqw)>0){
            throw new ServiceException(-1,"该用户已经注册");
        }
        this.saveOrUpdate(user);
    }
}
